package com.bins.knowledge.point.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class SimpleClientHandler extends ChannelInboundHandlerAdapter {

    // 当客户端连接成功后触发该方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端已连接");
        // 连接成功后发送消息给服务端
        ctx.writeAndFlush(Unpooled.copiedBuffer("Hello from client", CharsetUtil.UTF_8));
    }

    // 当从服务端接收到消息时触发该方法
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("客户端收到消息: " + buf.toString(CharsetUtil.UTF_8));
    }

    // 当发生异常时触发该方法
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close(); // 发生异常时关闭连接
    }
}